/*
 * Copyright (c) 2023 HPMicro
 * SPDX-License-Identifier: BSD-3-Clause
 *
 *
 */

#include "board.h"
#include "hpm_uart_drv.h"
#include "hpm_gptmr_drv.h"
#include "hpm_lcdc_drv.h"
#include "hpm_i2c_drv.h"
#include "hpm_gpio_drv.h"
#include "pinmux.h"
#include "hpm_pmp_drv.h"
#include "hpm_clock_drv.h"
#include "hpm_sysctl_drv.h"
#include "hpm_pllctlv2_drv.h"
#include "hpm_sdxc_drv.h"
#include "hpm_ddrctl_regs.h"
#include "hpm_ddrphy_regs.h"
#include "hpm_pcfg_drv.h"
#include "hpm_pixelmux_drv.h"
#include "hpm_lvb_drv.h"
#include "hpm_enet_drv.h"
#include "hpm_usb_drv.h"
#include "hpm_mipi_dsi_drv.h"
#include "hpm_mipi_dsi_phy_drv.h"

static board_timer_cb timer_cb;

/**
 * @brief FLASH configuration option definitions:
 * option[0]:
 *    [31:16] 0xfcf9 - FLASH configuration option tag
 *    [15:4]  0 - Reserved
 *    [3:0]   option words (exclude option[0])
 * option[1]:
 *    [31:28] Flash probe type
 *      0 - SFDP SDR / 1 - SFDP DDR
 *      2 - 1-4-4 Read (0xEB, 24-bit address) / 3 - 1-2-2 Read(0xBB, 24-bit address)
 *      4 - HyperFLASH 1.8V / 5 - HyperFLASH 3V
 *      6 - OctaBus DDR (SPI -> OPI DDR)
 *      8 - Xccela DDR (SPI -> OPI DDR)
 *      10 - EcoXiP DDR (SPI -> OPI DDR)
 *    [27:24] Command Pads after Power-on Reset
 *      0 - SPI / 1 - DPI / 2 - QPI / 3 - OPI
 *    [23:20] Command Pads after Configuring FLASH
 *      0 - SPI / 1 - DPI / 2 - QPI / 3 - OPI
 *    [19:16] Quad Enable Sequence (for the device support SFDP 1.0 only)
 *      0 - Not needed
 *      1 - QE bit is at bit 6 in Status Register 1
 *      2 - QE bit is at bit1 in Status Register 2
 *      3 - QE bit is at bit7 in Status Register 2
 *      4 - QE bit is at bit1 in Status Register 2 and should be programmed by 0x31
 *    [15:8] Dummy cycles
 *      0 - Auto-probed / detected / default value
 *      Others - User specified value, for DDR read, the dummy cycles should be 2 * cycles on FLASH datasheet
 *    [7:4] Misc.
 *      0 - Not used
 *      1 - SPI mode
 *      2 - Internal loopback
 *      3 - External DQS
 *    [3:0] Frequency option
 *      1 - 30MHz / 2 - 50MHz / 3 - 66MHz / 4 - 80MHz / 5 - 100MHz / 6 - 120MHz / 7 - 133MHz / 8 - 166MHz
 *
 * option[2] (Effective only if the bit[3:0] in option[0] > 1)
 *    [31:20]  Reserved
 *    [19:16] IO voltage
 *      0 - 3V / 1 - 1.8V
 *    [15:12] Pin group
 *      0 - 1st group / 1 - 2nd group
 *    [11:8] Connection selection
 *      0 - CA_CS0 / 1 - CB_CS0 / 2 - CA_CS0 + CB_CS0 (Two FLASH connected to CA and CB respectively)
 *    [7:0] Drive Strength
 *      0 - Default value
 * option[3] (Effective only if the bit[3:0] in option[0] > 2, required only for the QSPI NOR FLASH that not supports
 *              JESD216)
 *    [31:16] reserved
 *    [15:12] Sector Erase Command Option, not required here
 *    [11:8]  Sector Size Option, not required here
 *    [7:0] Flash Size Option
 *      0 - 4MB / 1 - 8MB / 2 - 16MB
 */
#if defined(FLASH_XIP) && FLASH_XIP
__attribute__((section(".nor_cfg_option"))) const uint32_t option[4] = { 0xfcf90001, 0x00000007, 0x0, 0x0 };
#endif

#if defined(FLASH_UF2) && FLASH_UF2
ATTR_PLACE_AT(".uf2_signature") const uint32_t uf2_signature = BOARD_UF2_SIGNATURE;
#endif

void board_init_console(void)
{
#if !defined(CONFIG_NDEBUG_CONSOLE) || !CONFIG_NDEBUG_CONSOLE
#if BOARD_CONSOLE_TYPE == CONSOLE_TYPE_UART
    console_config_t cfg;

    /* uart needs to configure pin function before enabling clock, otherwise the level change of
     * uart rx pin when configuring pin function will cause a wrong data to be received.
     * And a uart rx dma request will be generated by default uart fifo dma trigger level.
     */
    init_uart_pins((UART_Type *) BOARD_CONSOLE_BASE);

    /* Configure the UART clock to 24MHz */
    clock_set_source_divider(BOARD_CONSOLE_CLK_NAME, clk_src_osc24m, 1U);
    clock_add_to_group(BOARD_CONSOLE_CLK_NAME, 0);

    cfg.type = BOARD_CONSOLE_TYPE;
    cfg.base = (uint32_t) BOARD_CONSOLE_BASE;
    cfg.src_freq_in_hz = clock_get_frequency(BOARD_CONSOLE_CLK_NAME);
    cfg.baudrate = BOARD_CONSOLE_BAUDRATE;

    if (status_success != console_init(&cfg)) {
        /* failed to  initialize debug console */
        while (1) {
        }
    }
#else
    while (1)
        ;
#endif
#endif
}

void board_print_clock_freq(void)
{
    printf("==============================\n");
    printf(" %s clock summary\n", BOARD_NAME);
    printf("==============================\n");
    printf("cpu0:\t\t %dHz\n", clock_get_frequency(clock_cpu0));
    printf("gpu0:\t\t %dHz\n", clock_get_frequency(clock_gpu0));
    printf("axis:\t\t %dHz\n", clock_get_frequency(clock_axis));
    printf("axic:\t\t %dHz\n", clock_get_frequency(clock_axic));
    printf("axif:\t\t %dHz\n", clock_get_frequency(clock_axif));
    printf("axid:\t\t %dHz\n", clock_get_frequency(clock_axid));
    printf("axiv:\t\t %dHz\n", clock_get_frequency(clock_axiv));
    printf("axig:\t\t %dHz\n", clock_get_frequency(clock_axig));
    printf("mchtmr0:\t %dHz\n", clock_get_frequency(clock_mchtmr0));
    printf("xpi0:\t\t %dHz\n", clock_get_frequency(clock_xpi0));
    printf("==============================\n");
}

void board_init_uart(UART_Type *ptr)
{
    /* configure uart's pin before opening uart's clock */
    init_uart_pins(ptr);
    board_init_uart_clock(ptr);
}

void board_print_banner(void)
{
    const uint8_t banner[] = { "\n\
----------------------------------------------------------------------\n\
$$\\   $$\\ $$$$$$$\\  $$\\      $$\\ $$\\\n\
$$ |  $$ |$$  __$$\\ $$$\\    $$$ |\\__|\n\
$$ |  $$ |$$ |  $$ |$$$$\\  $$$$ |$$\\  $$$$$$$\\  $$$$$$\\   $$$$$$\\\n\
$$$$$$$$ |$$$$$$$  |$$\\$$\\$$ $$ |$$ |$$  _____|$$  __$$\\ $$  __$$\\\n\
$$  __$$ |$$  ____/ $$ \\$$$  $$ |$$ |$$ /      $$ |  \\__|$$ /  $$ |\n\
$$ |  $$ |$$ |      $$ |\\$  /$$ |$$ |$$ |      $$ |      $$ |  $$ |\n\
$$ |  $$ |$$ |      $$ | \\_/ $$ |$$ |\\$$$$$$$\\ $$ |      \\$$$$$$  |\n\
\\__|  \\__|\\__|      \\__|     \\__|\\__| \\_______|\\__|       \\______/\n\
----------------------------------------------------------------------\n" };
#ifdef SDK_VERSION_STRING
    printf("hpm_sdk: %s\n", SDK_VERSION_STRING);
#endif
    printf("%s", banner);
}


uint8_t board_get_led_gpio_off_level(void)
{
    return BOARD_LED_OFF_LEVEL;
}

void board_ungate_mchtmr_at_lp_mode(void)
{
    /* Keep cpu clock on wfi, so that mchtmr irq can still work after wfi */
    sysctl_set_cpu0_lp_mode(HPM_SYSCTL, cpu_lp_mode_ungate_cpu_clock);
}

void board_init(void)
{
    board_init_clock();
    board_init_console();
    board_init_pmp();
#if BOARD_SHOW_CLOCK
    board_print_clock_freq();
#endif
#if BOARD_SHOW_BANNER
    board_print_banner();
#endif
}

void board_delay_us(uint32_t us)
{
    clock_cpu_delay_us(us);
}

void board_delay_ms(uint32_t ms)
{
    clock_cpu_delay_ms(ms);
}

void board_timer_isr(void)
{
    if (gptmr_check_status(BOARD_CALLBACK_TIMER, GPTMR_CH_RLD_STAT_MASK(BOARD_CALLBACK_TIMER_CH))) {
        gptmr_clear_status(BOARD_CALLBACK_TIMER, GPTMR_CH_RLD_STAT_MASK(BOARD_CALLBACK_TIMER_CH));
        timer_cb();
    }
}

SDK_DECLARE_EXT_ISR_M(BOARD_CALLBACK_TIMER_IRQ, board_timer_isr);

void board_timer_create(uint32_t ms, board_timer_cb cb)
{
    uint32_t gptmr_freq;
    gptmr_channel_config_t config;

    timer_cb = cb;
    gptmr_channel_get_default_config(BOARD_CALLBACK_TIMER, &config);

    clock_add_to_group(BOARD_CALLBACK_TIMER_CLK_NAME, 0);
    gptmr_freq = clock_get_frequency(BOARD_CALLBACK_TIMER_CLK_NAME);

    config.reload = gptmr_freq / 1000 * ms;
    gptmr_channel_config(BOARD_CALLBACK_TIMER, BOARD_CALLBACK_TIMER_CH, &config, false);
    gptmr_enable_irq(BOARD_CALLBACK_TIMER, GPTMR_CH_RLD_IRQ_MASK(BOARD_CALLBACK_TIMER_CH));
    intc_m_enable_irq_with_priority(BOARD_CALLBACK_TIMER_IRQ, 1);

    gptmr_start_counter(BOARD_CALLBACK_TIMER, BOARD_CALLBACK_TIMER_CH);
}

void board_i2c_bus_clear(I2C_Type *ptr)
{
    if (i2c_get_line_scl_status(ptr) == false) {
        printf("CLK is low, please power cycle the board\n");
        while (1) {
        }
    }
    if (i2c_get_line_sda_status(ptr) == false) {
        printf("SDA is low, try to issue I2C bus clear\n");
    } else {
        printf("I2C bus is ready\n");
        return;
    }
    i2s_gen_reset_signal(ptr, 9);
    board_delay_ms(100);
    printf("I2C bus is cleared\n");
}

void board_init_i2c(I2C_Type *ptr)
{
    hpm_stat_t stat;
    uint32_t freq;
    i2c_config_t config;

    init_i2c_pins(ptr);
    board_i2c_bus_clear(ptr);

    if (ptr == HPM_I2C0) {
        clock_add_to_group(clock_i2c0, 0);
        clock_set_source_divider(clock_i2c0, clk_src_osc24m, 1U);
        freq = clock_get_frequency(clock_i2c0);
    } else if (ptr == HPM_I2C1) {
        clock_add_to_group(clock_i2c1, 0);
        clock_set_source_divider(clock_i2c1, clk_src_osc24m, 1U);
        freq = clock_get_frequency(clock_i2c1);
    } else if (ptr == HPM_I2C2) {
        clock_add_to_group(clock_i2c2, 0);
        clock_set_source_divider(clock_i2c2, clk_src_osc24m, 1U);
        freq = clock_get_frequency(clock_i2c2);
    } else if (ptr == HPM_I2C3) {
        clock_add_to_group(clock_i2c3, 0);
        clock_set_source_divider(clock_i2c3, clk_src_osc24m, 1U);
        freq = clock_get_frequency(clock_i2c3);
    } else {
        printf("invild i2c base address 0x%lx\n", (uint32_t) ptr);
        while (1) {
        }
    }

    config.i2c_mode = i2c_mode_normal;
    config.is_10bit_addressing = false;
    stat = i2c_init_master(ptr, freq, &config);
    if (stat != status_success) {
        printf("failed to initialize i2c 0x%lx\n", (uint32_t) ptr);
        while (1) {
        }
    }
}

uint32_t board_init_spi_clock(SPI_Type *ptr)
{
    if (ptr == HPM_SPI1) {
        /* SPI1 clock configure */
        clock_add_to_group(clock_spi1, 0);
        return clock_get_frequency(clock_spi1);
    } else if (ptr == HPM_SPI2) {
        /* SPI2 clock configure */
        clock_add_to_group(clock_spi2, 0);
        return clock_get_frequency(clock_spi2);
    } else if (ptr == HPM_SPI3) {
        /* SPI3 clock configure */
        clock_add_to_group(clock_spi3, 0);
        return clock_get_frequency(clock_spi3);
    }
    return 0;
}

void board_init_gpio_pins(void)
{
    init_gpio_pins();
}

void board_init_spi_pins(SPI_Type *ptr)
{
    init_spi_pins(ptr);
}

void board_init_spi_pins_with_gpio_as_cs(SPI_Type *ptr)
{
    init_spi_pins_with_gpio_as_cs(ptr);
    gpio_set_pin_output_with_initial(BOARD_SPI_CS_GPIO_CTRL, GPIO_GET_PORT_INDEX(BOARD_SPI_CS_PIN),
                                     GPIO_GET_PIN_INDEX(BOARD_SPI_CS_PIN), !BOARD_SPI_CS_ACTIVE_LEVEL);
}

void board_write_spi_cs(uint32_t pin, uint8_t state)
{
    gpio_write_pin(BOARD_SPI_CS_GPIO_CTRL, GPIO_GET_PORT_INDEX(pin), GPIO_GET_PIN_INDEX(pin), state);
}

void board_init_led_pins(void)
{
    init_led_pins_as_gpio();
    gpio_set_pin_output_with_initial(BOARD_R_GPIO_CTRL, BOARD_R_GPIO_INDEX, BOARD_R_GPIO_PIN,
                                     board_get_led_gpio_off_level());
    gpio_set_pin_output_with_initial(BOARD_G_GPIO_CTRL, BOARD_G_GPIO_INDEX, BOARD_G_GPIO_PIN,
                                     board_get_led_gpio_off_level());
    gpio_set_pin_output_with_initial(BOARD_B_GPIO_CTRL, BOARD_B_GPIO_INDEX, BOARD_B_GPIO_PIN,
                                     board_get_led_gpio_off_level());
}

void board_led_toggle(void)
{
#ifdef BOARD_LED_TOGGLE_RGB
    static uint8_t i;
    switch (i) {
    case 1:
        gpio_write_pin(BOARD_R_GPIO_CTRL, BOARD_R_GPIO_INDEX, BOARD_R_GPIO_PIN, BOARD_LED_OFF_LEVEL);
        gpio_write_pin(BOARD_G_GPIO_CTRL, BOARD_G_GPIO_INDEX, BOARD_G_GPIO_PIN, BOARD_LED_ON_LEVEL);
        gpio_write_pin(BOARD_B_GPIO_CTRL, BOARD_B_GPIO_INDEX, BOARD_B_GPIO_PIN, BOARD_LED_OFF_LEVEL);
        break;

    case 2:
        gpio_write_pin(BOARD_R_GPIO_CTRL, BOARD_R_GPIO_INDEX, BOARD_R_GPIO_PIN, BOARD_LED_OFF_LEVEL);
        gpio_write_pin(BOARD_G_GPIO_CTRL, BOARD_G_GPIO_INDEX, BOARD_G_GPIO_PIN, BOARD_LED_OFF_LEVEL);
        gpio_write_pin(BOARD_B_GPIO_CTRL, BOARD_B_GPIO_INDEX, BOARD_B_GPIO_PIN, BOARD_LED_ON_LEVEL);
        break;

    case 0:
    default:
        gpio_write_pin(BOARD_R_GPIO_CTRL, BOARD_R_GPIO_INDEX, BOARD_R_GPIO_PIN, BOARD_LED_ON_LEVEL);
        gpio_write_pin(BOARD_G_GPIO_CTRL, BOARD_G_GPIO_INDEX, BOARD_G_GPIO_PIN, BOARD_LED_OFF_LEVEL);
        gpio_write_pin(BOARD_B_GPIO_CTRL, BOARD_B_GPIO_INDEX, BOARD_B_GPIO_PIN, BOARD_LED_OFF_LEVEL);
        break;
    }
    i++;
    i = i % 3;
#else
    gpio_toggle_pin(BOARD_LED_GPIO_CTRL, BOARD_LED_GPIO_INDEX, BOARD_LED_GPIO_PIN);
#endif
}

void board_led_write(uint8_t state)
{
    gpio_write_pin(BOARD_LED_GPIO_CTRL, BOARD_LED_GPIO_INDEX, BOARD_LED_GPIO_PIN, state);
}

void board_init_pmp(void)
{
    extern uint32_t __noncacheable_start__[];
    extern uint32_t __noncacheable_end__[];

    uint32_t start_addr = (uint32_t) __noncacheable_start__;
    uint32_t end_addr = (uint32_t) __noncacheable_end__;
    uint32_t length = end_addr - start_addr;

    if (length == 0) {
        return;
    }

    /* Ensure the address and the length are power of 2 aligned */
    assert((length & (length - 1U)) == 0U);
    assert((start_addr & (length - 1U)) == 0U);

    pmp_entry_t pmp_entry[3] = { 0 };
    pmp_entry[0].pmp_addr = PMP_NAPOT_ADDR(0x0000000, 0x80000000);
    pmp_entry[0].pmp_cfg.val = PMP_CFG(READ_EN, WRITE_EN, EXECUTE_EN, ADDR_MATCH_NAPOT, REG_UNLOCK);


    pmp_entry[1].pmp_addr = PMP_NAPOT_ADDR(0x80000000, 0x80000000);
    pmp_entry[1].pmp_cfg.val = PMP_CFG(READ_EN, WRITE_EN, EXECUTE_EN, ADDR_MATCH_NAPOT, REG_UNLOCK);

    pmp_entry[2].pmp_addr = PMP_NAPOT_ADDR(start_addr, length);
    pmp_entry[2].pmp_cfg.val = PMP_CFG(READ_EN, WRITE_EN, EXECUTE_EN, ADDR_MATCH_NAPOT, REG_UNLOCK);
    pmp_entry[2].pma_addr = PMA_NAPOT_ADDR(start_addr, length);
    pmp_entry[2].pma_cfg.val = PMA_CFG(ADDR_MATCH_NAPOT, MEM_TYPE_MEM_NON_CACHE_BUF, AMO_EN);
    pmp_config(&pmp_entry[0], ARRAY_SIZE(pmp_entry));
}

void board_init_display_system_clock(void)
{
    clock_add_to_group(clock_gpu0, 0);
    clock_add_to_group(clock_gwc0, 0);
    clock_add_to_group(clock_gwc1, 0);
    clock_add_to_group(clock_lvb, 0);
    clock_add_to_group(clock_lcb, 0);
    clock_add_to_group(clock_lcd0, 0);
    clock_add_to_group(clock_dsi0, 0);
    clock_add_to_group(clock_dsi1, 0);
    clock_add_to_group(clock_cam0, 0);
    clock_add_to_group(clock_cam1, 0);
    clock_add_to_group(clock_jpeg, 0);
    clock_add_to_group(clock_pdma, 0);
}

void board_init_clock(void)
{
    uint32_t cpu0_freq = clock_get_frequency(clock_cpu0);
    if (cpu0_freq == PLLCTL_SOC_PLL_REFCLK_FREQ) {
        /* Configure the External OSC ramp-up time: ~9ms */
        pllctlv2_xtal_set_rampup_time(HPM_PLLCTLV2, 32UL * 1000UL * 9U);

        /* Select clock setting preset1 */
        sysctl_clock_set_preset(HPM_SYSCTL, 2);
    }
    /* Add most Clocks to group 0 */
    /* not open uart clock in this API, uart should configure pin function before opening clock */
    clock_add_to_group(clock_cpu0, 0);
    clock_add_to_group(clock_ahb, 0);
    clock_add_to_group(clock_axic, 0);
    clock_add_to_group(clock_axis, 0);
    clock_add_to_group(clock_axiv, 0);
    clock_add_to_group(clock_axid, 0);
    clock_add_to_group(clock_axig, 0);

    clock_add_to_group(clock_mchtmr0, 0);
    clock_add_to_group(clock_xpi0, 0);
    clock_add_to_group(clock_gptmr0, 0);
    clock_add_to_group(clock_gptmr1, 0);
    clock_add_to_group(clock_gptmr2, 0);
    clock_add_to_group(clock_gptmr3, 0);
    clock_add_to_group(clock_i2c0, 0);
    clock_add_to_group(clock_i2c1, 0);
    clock_add_to_group(clock_i2c2, 0);
    clock_add_to_group(clock_i2c3, 0);
    clock_add_to_group(clock_spi0, 0);
    clock_add_to_group(clock_spi1, 0);
    clock_add_to_group(clock_spi2, 0);
    clock_add_to_group(clock_spi3, 0);
    clock_add_to_group(clock_can0, 0);
    clock_add_to_group(clock_can1, 0);
    clock_add_to_group(clock_can2, 0);
    clock_add_to_group(clock_can3, 0);
    clock_add_to_group(clock_can4, 0);
    clock_add_to_group(clock_can5, 0);
    clock_add_to_group(clock_can6, 0);
    clock_add_to_group(clock_can7, 0);
    clock_add_to_group(clock_ptpc, 0);
    clock_add_to_group(clock_ref0, 0);
    clock_add_to_group(clock_ref1, 0);
    clock_add_to_group(clock_watchdog0, 0);
    clock_add_to_group(clock_sdp, 0);
    clock_add_to_group(clock_xdma, 0);
    clock_add_to_group(clock_xram, 0);
    clock_add_to_group(clock_usb0, 0);
    clock_add_to_group(clock_kman, 0);
    clock_add_to_group(clock_gpio, 0);
    clock_add_to_group(clock_mbx0, 0);
    clock_add_to_group(clock_hdma, 0);
    clock_add_to_group(clock_rng, 0);
    clock_add_to_group(clock_adc0, 0);
    clock_add_to_group(clock_adc1, 0);
    clock_add_to_group(clock_crc0, 0);
    clock_add_to_group(clock_dao, 0);
    clock_add_to_group(clock_pdm, 0);
    clock_add_to_group(clock_smix, 0);

    clock_add_to_group(clock_i2s0, 0);
    clock_add_to_group(clock_i2s1, 0);
    clock_add_to_group(clock_i2s2, 0);
    clock_add_to_group(clock_i2s3, 0);

    clock_add_to_group(clock_eth0, 0);
    clock_add_to_group(clock_ffa, 0);

    board_init_display_system_clock();

    /* Connect Group0 to CPU0 */
    clock_connect_group_to_cpu(0, 0);

    /* Bump up DCDC voltage to 1150mv */
    pcfg_dcdc_set_voltage(HPM_PCFG, 1150);

    /* Configure PLL1_CLK0 Post Divider to 1 */
    pllctlv2_set_postdiv(HPM_PLLCTLV2, 0, 0, 0);
    pllctlv2_init_pll_with_freq(HPM_PLLCTLV2, 0, BOARD_CPU_FREQ);

    /* Configure axis to 200MHz */
    clock_set_source_divider(clock_axis, clk_src_pll1_clk0, 4);

    /* Configure axig/clock_gpu0 to 400MHz */
    clock_set_source_divider(clock_axig, clk_src_pll1_clk0, 2);

    /* Configure mchtmr to 24MHz */
    clock_set_source_divider(clock_mchtmr0, clk_src_osc24m, 1);

    clock_update_core_clock();
}

void board_init_can(MCAN_Type *ptr)
{
    init_can_pins(ptr);
}

uint32_t board_init_can_clock(MCAN_Type *ptr)
{
    uint32_t freq = 0;
    if (ptr == HPM_MCAN0) {
        /* Set the CAN0 peripheral clock to 80MHz */
        clock_set_source_divider(clock_can0, clk_src_pll1_clk0, 10);
        freq = clock_get_frequency(clock_can0);
    } else if (ptr == HPM_MCAN1) {
        /* Set the CAN1 peripheral clock to 80MHz */
        clock_set_source_divider(clock_can1, clk_src_pll1_clk0, 10);
        freq = clock_get_frequency(clock_can1);
    } else if (ptr == HPM_MCAN2) {
        /* Set the CAN2 peripheral clock to 8MHz */
        clock_set_source_divider(clock_can2, clk_src_pll1_clk0, 10);
        freq = clock_get_frequency(clock_can2);
    } else if (ptr == HPM_MCAN3) {
        /* Set the CAN3 peripheral clock to 80MHz */
        clock_set_source_divider(clock_can3, clk_src_pll1_clk0, 10);
        freq = clock_get_frequency(clock_can3);
    } else if (ptr == HPM_MCAN4) {
        /* Set the CAN4 peripheral clock to 80MHz */
        clock_set_source_divider(clock_can4, clk_src_pll1_clk0, 10);
        freq = clock_get_frequency(clock_can4);
    } else if (ptr == HPM_MCAN5) {
        /* Set the CAN5 peripheral clock to 80MHz */
        clock_set_source_divider(clock_can5, clk_src_pll1_clk0, 10);
        freq = clock_get_frequency(clock_can5);
    } else if (ptr == HPM_MCAN6) {
        /* Set the CAN6 peripheral clock to 80MHz */
        clock_set_source_divider(clock_can6, clk_src_pll1_clk0, 10);
        freq = clock_get_frequency(clock_can6);
    } else if (ptr == HPM_MCAN7) {
        /* Set the CAN7 peripheral clock to 80MHz */
        clock_set_source_divider(clock_can7, clk_src_pll1_clk0, 10);
        freq = clock_get_frequency(clock_can7);
    } else {
        /* Invalid CAN instance */
    }
    return freq;
}

uint32_t board_init_uart_clock(UART_Type *ptr)
{
    uint32_t freq = 0U;
    if (ptr == HPM_UART0) {
        clock_set_source_divider(clock_uart0, clk_src_osc24m, 1);
        clock_add_to_group(clock_uart0, 0);
        freq = clock_get_frequency(clock_uart0);
    } else if (ptr == HPM_UART1) {
        clock_set_source_divider(clock_uart1, clk_src_osc24m, 1);
        clock_add_to_group(clock_uart1, 0);
        freq = clock_get_frequency(clock_uart1);
    } else if (ptr == HPM_UART2) {
        clock_set_source_divider(clock_uart2, clk_src_osc24m, 1);
        clock_add_to_group(clock_uart2, 0);
        freq = clock_get_frequency(clock_uart2);
    } else {
        /* Not supported */
    }
    return freq;
}

uint32_t board_lcdc_clock_init(clock_name_t clock_name, uint32_t pixel_clk_khz);

#if defined(CONFIG_PANEL_RGB_TM070RDH13) && CONFIG_PANEL_RGB_TM070RDH13
static void set_reset_pin_level_tm070rdh13(uint8_t level)
{
    gpio_write_pin(HPM_GPIO0, GPIO_DO_GPIOA, 14, level);
}

static void set_backlight_tm070rdh13(uint16_t percent)
{
    gpio_write_pin(HPM_GPIO0, GPIO_DO_GPIOA, 9, percent > 0 ? 1 : 0);
}

static void set_video_router_tm070rdh13(void)
{
    pixelmux_rgb_data_source_enable(pixelmux_rgb_sel_lcdc0);
}

void board_init_lcd_rgb_tm070rdh13(void)
{
    init_lcd_rgb_ctl_pins();
    init_lcd_rgb_pins();

    gpio_set_pin_output(HPM_GPIO0, GPIO_DO_GPIOY, 5);
    gpio_write_pin(HPM_GPIO0, GPIO_DO_GPIOY, 5, 1);

    gpio_set_pin_output(HPM_GPIO0, GPIO_DO_GPIOA, 9);
    gpio_set_pin_output(HPM_GPIO0, GPIO_DO_GPIOA, 14);

    hpm_panel_hw_interface_t hw_if = {0};
    hpm_panel_t *panel = hpm_panel_find_device_default();
    const hpm_panel_timing_t *timing = hpm_panel_get_timing(panel);
    uint32_t lcdc_pixel_clk_khz = board_lcdc_clock_init(clock_lcd0, timing->pixel_clock_khz);
    hw_if.set_reset_pin_level = set_reset_pin_level_tm070rdh13;
    hw_if.set_backlight = set_backlight_tm070rdh13;
    hw_if.set_video_router = set_video_router_tm070rdh13;
    hw_if.lcdc_pixel_clk_khz = lcdc_pixel_clk_khz;
    hpm_panel_register_interface(panel, &hw_if);

    printf("name: %s, lcdc_clk: %ukhz\n",
                        hpm_panel_get_name(panel),
                        lcdc_pixel_clk_khz);

    hpm_panel_reset(panel);
    hpm_panel_init(panel);
    hpm_panel_power_on(panel);
}

#endif

#if defined(CONFIG_PANEL_LVDS_CC10128007) && CONFIG_PANEL_LVDS_CC10128007
static void set_backlight_cc10128007(uint16_t percent)
{
    gpio_write_pin(HPM_GPIO0, GPIO_DO_GPIOA, 31, percent > 0 ? 1 : 0);
    gpio_write_pin(HPM_GPIO0, GPIO_DO_GPIOA, 30, percent > 0 ? 1 : 0);
}

static void set_video_router_cc10128007(void)
{
    pixelmux_config_tx_phy1_mode(pixelmux_tx_phy_mode_lvds);
    pixelmux_lvb_di0_data_source_enable(pixelmux_lvb_di0_sel_lcdc0);
}

void board_init_lcd_lvds_cc10128007(void)
{
    init_lcd_lvds_single_ctl_pins();
    gpio_set_pin_output(HPM_GPIO0, GPIO_DO_GPIOA, 30);
    gpio_set_pin_output(HPM_GPIO0, GPIO_DO_GPIOA, 31);

    init_mipi_lvds_tx_phy1_pin();

    hpm_panel_hw_interface_t hw_if = {0};
    hpm_panel_t *panel = hpm_panel_find_device_default();
    const hpm_panel_timing_t *timing = hpm_panel_get_timing(panel);

    uint32_t lcdc_pixel_clk_khz = board_lcdc_clock_init(clock_lcd0, timing->pixel_clock_khz);
    hw_if.set_video_router = set_video_router_cc10128007;
    hw_if.set_backlight = set_backlight_cc10128007;
    hw_if.lcdc_pixel_clk_khz = lcdc_pixel_clk_khz;
    hw_if.video.lvds.channel_di_index = 0;
    hw_if.video.lvds.channel_index = 1; /* ch1 -> phy1*/
    hw_if.video.lvds.lvb_base = HPM_LVB;

    hpm_panel_register_interface(panel, &hw_if);

    printf("name: %s, lcdc_clk: %ukhz\n",
                        hpm_panel_get_name(panel),
                        lcdc_pixel_clk_khz);

    hpm_panel_reset(panel);
    hpm_panel_init(panel);
    hpm_panel_power_on(panel);
}
#endif

#if defined(CONFIG_PANEL_MIPI_MC10128007_31B) && CONFIG_PANEL_MIPI_MC10128007_31B
static void set_reset_pin_level_mc10128007_31b(uint8_t level)
{
    gpio_write_pin(HPM_GPIO0, GPIO_DO_GPIOB, 1, level);
}

static void set_video_router_mc10128007_31b(void)
{
    pixelmux_mipi_dsi0_data_source_enable(pixelmux_mipi_dsi0_sel_lcdc0);
    pixelmux_config_tx_phy0_mode(pixelmux_tx_phy_mode_mipi);
}

void board_init_lcd_mipi_mc10128007_31b(void)
{
    /* RESET */
    init_lcd_mipi_ctl_pins();
    gpio_set_pin_output(HPM_GPIO0, GPIO_DO_GPIOB, 1);

    init_mipi_lvds_tx_phy0_pin();

    hpm_panel_hw_interface_t hw_if = {0};
    hpm_panel_t *panel = hpm_panel_find_device_default();
    const hpm_panel_timing_t *timing = hpm_panel_get_timing(panel);
    uint32_t lcdc_pixel_clk_khz = board_lcdc_clock_init(clock_lcd0, timing->pixel_clock_khz);
    hw_if.set_reset_pin_level = set_reset_pin_level_mc10128007_31b;
    hw_if.set_video_router = set_video_router_mc10128007_31b;
    hw_if.lcdc_pixel_clk_khz = lcdc_pixel_clk_khz;
    hw_if.video.mipi.format = HPM_PANEL_MIPI_FORMAT_RGB888;
    hw_if.video.mipi.mipi_host_base = HPM_MIPI_DSI0;
    hw_if.video.mipi.mipi_phy_base = HPM_MIPI_DSI_PHY0;
    hpm_panel_register_interface(panel, &hw_if);

    printf("name: %s, lcdc_clk: %ukhz\n",
                        hpm_panel_get_name(panel),
                        lcdc_pixel_clk_khz);

    hpm_panel_reset(panel);
    hpm_panel_init(panel);
    hpm_panel_power_on(panel);
}
#endif

#if defined(CONFIG_PANEL_LVDS_TM103XDGP01) && CONFIG_PANEL_LVDS_TM103XDGP01
static void set_reset_pin_level_tm103xdgp01(uint8_t level)
{
    gpio_write_pin(HPM_GPIO0, GPIO_DO_GPIOA, 31, level);
}

static void set_video_router_tm103xdgp01(void)
{
    pixelmux_config_tx_phy0_mode(pixelmux_tx_phy_mode_lvds);
    pixelmux_config_tx_phy1_mode(pixelmux_tx_phy_mode_lvds);

    pixelmux_lvb_di1_data_source_enable(pixelmux_lvb_di1_sel_lcdc0);
    pixelmux_lvb_di0_data_source_enable(pixelmux_lvb_di0_sel_lcdc0);
}

void board_init_lcd_lvds_tm103xdgp01(void)
{
    init_lcd_lvds_double_ctl_pins();
    gpio_set_pin_output(HPM_GPIO0, GPIO_DO_GPIOA, 31);

    init_mipi_lvds_tx_phy0_pin();
    init_mipi_lvds_tx_phy1_pin();

    hpm_panel_hw_interface_t hw_if = {0};
    hpm_panel_t *panel = hpm_panel_find_device_default();
    const hpm_panel_timing_t *timing = hpm_panel_get_timing(panel);

    /* In split mode: lcdc_pixel_clk = 2 * panel_pixel_clk */
    uint32_t lcdc_pixel_clk_khz = board_lcdc_clock_init(clock_lcd0, timing->pixel_clock_khz * 2);
    hw_if.set_reset_pin_level = set_reset_pin_level_tm103xdgp01;
    hw_if.set_video_router = set_video_router_tm103xdgp01;
    hw_if.lcdc_pixel_clk_khz = lcdc_pixel_clk_khz;
    hw_if.video.lvds.channel_di_index = 0;
    hw_if.video.lvds.lvb_base = HPM_LVB;

    hpm_panel_register_interface(panel, &hw_if);

    printf("name: %s, lcdc_clk: %ukhz\n",
                        hpm_panel_get_name(panel),
                        lcdc_pixel_clk_khz);

    hpm_panel_reset(panel);
    hpm_panel_init(panel);
    hpm_panel_power_on(panel);
}
#endif

#ifdef CONFIG_HPM_PANEL

void board_lcd_backlight(bool is_on)
{
    hpm_panel_t *panel = hpm_panel_find_device_default();
    hpm_panel_set_backlight(panel, is_on == true ? 100 : 0);
}

uint32_t board_lcdc_clock_init(clock_name_t clock_name, uint32_t pixel_clk_khz)
{
    clock_add_to_group(clock_name, 0);

    uint32_t freq_khz = clock_get_frequency(clk_pll4clk0) / 1000;
    uint32_t div = (freq_khz + pixel_clk_khz / 2) / pixel_clk_khz;
    clock_set_source_divider(clock_name, clk_src_pll4_clk0, div);
    return clock_get_frequency(clock_name) / 1000;
}

void board_init_lcd(void)
{
#if defined(CONFIG_PANEL_RGB_TM070RDH13) && CONFIG_PANEL_RGB_TM070RDH13
    board_init_lcd_rgb_tm070rdh13();
#endif

#if defined(CONFIG_PANEL_LVDS_CC10128007) && CONFIG_PANEL_LVDS_CC10128007
    board_init_lcd_lvds_cc10128007();
#endif

#if defined(CONFIG_PANEL_MIPI_MC10128007_31B) && CONFIG_PANEL_MIPI_MC10128007_31B
    board_init_lcd_mipi_mc10128007_31b();
#endif

#if defined(CONFIG_PANEL_LVDS_TM103XDGP01) && CONFIG_PANEL_LVDS_TM103XDGP01
    board_init_lcd_lvds_tm103xdgp01();
#endif
}

void board_panel_para_to_lcdc(lcdc_config_t *config)
{
    const hpm_panel_timing_t *timing;
    hpm_panel_t *panel = hpm_panel_find_device_default();

    timing = hpm_panel_get_timing(panel);
    config->resolution_x = timing->hactive;
    config->resolution_y = timing->vactive;

    config->hsync.pulse_width = timing->hsync_len;
    config->hsync.back_porch_pulse = timing->hback_porch;
    config->hsync.front_porch_pulse = timing->hfront_porch;

    config->vsync.pulse_width = timing->vsync_len;
    config->vsync.back_porch_pulse = timing->vback_porch;
    config->vsync.front_porch_pulse = timing->vfront_porch;

    config->control.invert_hsync = timing->hsync_pol;
    config->control.invert_vsync = timing->vsync_pol;
    config->control.invert_href = timing->de_pol;
    config->control.invert_pixel_data = timing->pixel_data_pol;
    config->control.invert_pixel_clock = timing->pixel_clk_pol;
}
#endif

void board_init_gwc(void)
{
    clock_add_to_group(clock_gwc0, 0);
    clock_add_to_group(clock_gwc1, 0);
    clock_add_to_group(clock_lcd0, 0);
}

void board_init_cap_touch(void)
{
    init_cap_pins();
    gpio_set_pin_output_with_initial(BOARD_CAP_RST_GPIO, BOARD_CAP_RST_GPIO_INDEX, BOARD_CAP_RST_GPIO_PIN, 0);
    gpio_set_pin_output_with_initial(BOARD_CAP_INTR_GPIO, BOARD_CAP_INTR_GPIO_INDEX, BOARD_CAP_INTR_GPIO_PIN, 0);

    board_delay_ms(1);
    gpio_write_pin(BOARD_CAP_INTR_GPIO, BOARD_CAP_INTR_GPIO_INDEX, BOARD_CAP_INTR_GPIO_PIN, 0);
    board_delay_ms(1);
    gpio_write_pin(BOARD_CAP_RST_GPIO, BOARD_CAP_RST_GPIO_INDEX, BOARD_CAP_RST_GPIO_PIN, 1);
    board_delay_ms(6);
    gpio_write_pin(BOARD_CAP_RST_GPIO, BOARD_CAP_INTR_GPIO_INDEX, BOARD_CAP_INTR_GPIO_PIN, 0);

    board_init_i2c(BOARD_CAP_I2C_BASE);
}

void board_init_cam_pins(void)
{
    init_cam_pins();
    /* enable cam RST pin out with high level */
    gpio_set_pin_output_with_initial(BOARD_CAM_RST_GPIO_CTRL, BOARD_CAM_RST_GPIO_INDEX, BOARD_CAM_RST_GPIO_PIN, 1);
    /* PWDN pin set to low when power up */
    gpio_set_pin_output_with_initial(BOARD_CAM_PWDN_GPIO_CTRL, BOARD_CAM_PWDN_GPIO_INDEX, BOARD_CAM_PWDN_GPIO_PIN, 0);
    pixelmux_cam0_data_source_enable(pixelmux_cam0_sel_dvp);
}

void board_write_cam_rst(uint8_t state)
{
    gpio_write_pin(BOARD_CAM_RST_GPIO_CTRL, BOARD_CAM_RST_GPIO_INDEX, BOARD_CAM_RST_GPIO_PIN, state);
}

void board_write_cam_pwdn(uint8_t state)
{
    gpio_write_pin(BOARD_CAM_PWDN_GPIO_CTRL, BOARD_CAM_PWDN_GPIO_INDEX, BOARD_CAM_PWDN_GPIO_PIN, state);
}

uint32_t board_init_cam_clock(CAM_Type *ptr)
{
    uint32_t freq = 0;
    if (ptr == HPM_CAM0) {
        /* Configure camera clock to 24MHz */
        clock_set_source_divider(clock_cam0, clk_src_osc24m, 1U);
        freq = clock_get_frequency(clock_cam0);
    } else if (ptr == HPM_CAM1) {
        /* Configure camera clock to 24MHz */
        clock_set_source_divider(clock_cam1, clk_src_osc24m, 1U);
        freq = clock_get_frequency(clock_cam1);
    } else {
        /* Invalid camera instance */
    }
    return freq;
}

void board_init_mipi_csi_cam_pins(void)
{
    init_cam_mipi_csi_pins();
    init_mipi_lvds_rx_phy1_pin();

    /* enable cam RST pin out with high level */
    gpio_set_pin_output_with_initial(HPM_GPIO0, GPIO_DI_GPIOB, 0, 1);
}

void board_write_mipi_csi_cam_rst(uint8_t state)
{
    gpio_write_pin(HPM_GPIO0, GPIO_DI_GPIOB, 0, state);
}


static void _cpu_wait_ms(uint32_t cpu_freq, uint32_t ms)
{
    uint32_t ticks_per_us = (cpu_freq + 1000000UL - 1UL) / 1000000UL;
    uint64_t expected_ticks = hpm_csr_get_core_mcycle() + (uint64_t)ticks_per_us * 1000UL * ms;
    while (hpm_csr_get_core_mcycle() < expected_ticks) {
    }
}

void init_ddr2_800(void)
{
    /* Enable On-chip DCDC 1.8V output */
    HPM_PCFG->DCDCM_MODE = PCFG_DCDCM_MODE_VOLT_SET(1800) | PCFG_DCDCM_MODE_MODE_SET(1);

    /* Change DDR clock to 200MHz, namely: DDR2-800 */
    clock_set_source_divider(clock_axif, clk_src_pll1_clk0, 4);

    /* Enable DDR clock first */
    clock_add_to_group(clock_ddr0, 0);

    /* Wait until the clock is stable */
    uint32_t core_clock_freq = clock_get_frequency(clock_cpu0);
    _cpu_wait_ms(core_clock_freq, 5);

    /* Clear DFI_INIT_COMPLETE_EN bit */
    HPM_DDRCTL->DFIMISC &= ~DDRCTL_DFIMISC_DFI_INIT_COMPLETE_EN_MASK;

    /* Release DDR core reset */
    *(volatile uint32_t *) (HPM_DDRCTL_BASE + 0x3000UL) |= (1UL << 26);

    /* Enable PORT */
    HPM_DDRCTL->PCFG[0].CTRL = 1;

    /* Configure W972GG6KB parameters, configure DDRCTL first */
    HPM_DDRCTL->MSTR = DDRCTL_MSTR_ACTIVE_RANKS_SET(1)      /* RANK=1 */
                       | DDRCTL_MSTR_BURST_RDWR_SET(4)        /* Burst Length = 8 */
                       | DDRCTL_MSTR_DATA_BUS_WIDTH_SET(0)    /* Full DQ bus width */
                       | DDRCTL_MSTR_DDR3_SET(0);             /* DDR2 Device */

    /* Skip SDRAM Initialization in controller, the initialization sequence will be performed by PHY */
    HPM_DDRCTL->INIT0 = DDRCTL_INIT0_SKIP_DRAM_INIT_SET(1)
                        | DDRCTL_INIT0_POST_CKE_X1024_SET(2)    /* Default setting */
                        | DDRCTL_INIT0_PRE_CKE_X1024_SET(0x4e); /* Default setting */

    /* Configure DFI timing */
    HPM_DDRCTL->DFITMG0 = 0x03010101UL;
    HPM_DDRCTL->DFITMG1 = 0x00020101UL;
    HPM_DDRCTL->DFIUPD0 = 0x40005UL;
    HPM_DDRCTL->DFIUPD1 = 0x00020008UL;

    HPM_DDRCTL->ODTCFG = 0x06000600UL;    /* BL=8 */

    /* Configure ADDRMAP */
    HPM_DDRCTL->ADDRMAP0 = 0x001F1F1FUL;  /* RANK0 not used */
    HPM_DDRCTL->ADDRMAP1 = 0x00121212UL;  /* HIF bit[24:22] as BANK[2:0] */
    HPM_DDRCTL->ADDRMAP2 = 0;             /* HIF bit[6:3] as COL_B[6:3] */
    HPM_DDRCTL->ADDRMAP3 = 0;             /* HIF bit [10:7] as COL_B[11,9:6:7] */
    HPM_DDRCTL->ADDRMAP4 = 0xF0FUL;       /* not used */
    HPM_DDRCTL->ADDRMAP5 = 0x06030303UL;  /* HIF bit[21:11] as ROW[10:0], HIF bit[25] as ROW[11] */
    HPM_DDRCTL->ADDRMAP6 = 0x0F0F0606UL;  /* HIF bit[27:26] as ROW[13:12] */

    /* Release DDR AXI reset */
    *(volatile uint32_t *) (HPM_DDRCTL_BASE + 0x3000UL) |= (1UL << 27);

    /* Release DDR PHY */
    *(volatile uint32_t *) (HPM_DDRPHY_BASE + 0x3000UL) |= (1UL << 4);

    HPM_DDRPHY->DCR = DDRPHY_DCR_DDRMD_SET(2)       /* Set to DDR2 mode  */
                      | DDRPHY_DCR_DDR8BNK_MASK     /* BANK = 8 */
                      | DDRPHY_DCR_BYTEMASK_MASK;   /* BYTEMASK = 1 */
    HPM_DDRPHY->DSGCR |= DDRPHY_DSGCR_RRMODE_MASK;  /* Enable RRMode */

    /* Configure DDR2 registers */
    HPM_DDRPHY->MR = (3UL << 0)    /* BL = 3 */
                     | (0UL << 3)    /* BT = 0 */
                     | (6UL << 4)    /* CL = 6 */
                     | (0UL << 7)    /* Operating mode */
                     | (0UL << 8)    /* DLL Reset = 0 */
                     | (6UL << 9);   /* WR = 6  */
    HPM_DDRPHY->EMR = (1UL << 0)              /* DLL Enable */
                      | (0UL << 1)              /* Output Driver Impedance Control */
                      | (0UL << 6) | (1UL << 2) /* On Die Termination */
                      | (0UL << 3)              /* AL(Posted CAS Additive Latency) = 0 */
                      | (0UL << 7)              /* OCD = 0*/
                      | (0UL << 10)             /* DQS */
                      | (0UL << 11)             /* RDQS */
                      | (0UL << 12);            /* QOFF */
    HPM_DDRPHY->EMR2 = 0;
    HPM_DDRPHY->EMR3 = 0;
    HPM_DDRPHY->DTPR0 = (4UL << 0)
                        | (5UL << 4)
                        | (14UL << 8)
                        | (15UL << 12)
                        | (50UL << 16)
                        | (10UL << 22)
                        | (60 << 26);
    HPM_DDRPHY->DTPR1 = (2UL << 0)
                        | (31UL << 5)
                        | (80UL << 11)
                        | (40UL << 20)
                        | (0x8 << 26);
    HPM_DDRPHY->DTPR2 = (256UL << 0)
                        | (6UL << 10)
                        | (4UL << 15)
                        | (512UL << 19);

    /* tREFPRD */
    HPM_DDRPHY->PGCR2 = 0xF06D50;

    /* Set DFI_INIT_COMPLETE_EN bit */
    HPM_DDRCTL->DFIMISC |= DDRCTL_DFIMISC_DFI_INIT_COMPLETE_EN_MASK;

    /* Start PHY Init First */
    HPM_DDRPHY->PIR |= DDRPHY_PIR_INIT_MASK;
    while ((HPM_DDRPHY->PGSR0 & DDRPHY_PGSR0_IDONE_MASK) == 0) {
    }
    /** Data training
     * RANKEN = 1, Others: default value
     */
    HPM_DDRPHY->DTCR = 0x91003587UL;

    /* Trigger PHY to do the PHY initialization and DRAM initialization */
    HPM_DDRPHY->PIR = 0xF501UL;

    /* Wait until the initialization sequence started */
    while ((HPM_DDRPHY->PGSR0 & DDRPHY_PGSR0_IDONE_MASK) != 0) {
    }
    /* Wait until the initialization sequence completed */
    while ((HPM_DDRPHY->PGSR0 & DDRPHY_PGSR0_IDONE_MASK) == 0) {
    }

    /* Wait for normal mode */
    while ((HPM_DDRCTL->STAT & DDRCTL_STAT_OPERATING_MODE_MASK) != 0x1) {
    }
}

void init_ddr3l_1333(void)
{
    /* Enable On-chip DCDC 1.4V output */
    HPM_PCFG->DCDCM_MODE = PCFG_DCDCM_MODE_VOLT_SET(1400) | PCFG_DCDCM_MODE_MODE_SET(5);

    /* Change DDR clock to 333.33MHz, namely: DDR3-1333 */
    clock_set_source_divider(clock_axif, clk_src_pll1_clk1, 2);

    /* Enable DDR clock first */
    clock_add_to_group(clock_ddr0, 0);

    /* Wait until the clock is stable */
    uint32_t core_clock_freq = clock_get_frequency(clock_cpu0);
    _cpu_wait_ms(core_clock_freq, 5);

    /* Release DDR PHY */
    *(volatile uint32_t *) (HPM_DDRPHY_BASE + 0x3000UL) |= (1UL << 4);

    /* Clear DFI_INIT_COMPLETE_EN bit */
    HPM_DDRCTL->DFIMISC &= ~DDRCTL_DFIMISC_DFI_INIT_COMPLETE_EN_MASK;

    HPM_DDRPHY->DSGCR = 0xf004641f;

    *(volatile uint32_t *) (HPM_DDRPHY_BASE + 0x3000UL) |= (1UL << 0);

    /* Release DDR core reset */
    *(volatile uint32_t *) (HPM_DDRCTL_BASE + 0x3000UL) |= (1UL << 26);

    /* Configure DDRCTL first */
    HPM_DDRCTL->MSTR = DDRCTL_MSTR_ACTIVE_RANKS_SET(1)      /* RANK=1 */
                       | DDRCTL_MSTR_BURST_RDWR_SET(4)        /* Burst Length = 8 */
                       | DDRCTL_MSTR_DATA_BUS_WIDTH_SET(0)    /* Full DQ bus width */
                       | DDRCTL_MSTR_DDR3_SET(1);             /* DDR3 Device */

    /* Enable PORT */
    HPM_DDRCTL->PCFG[0].CTRL = 1;

    /* Skip SDRAM Initialization in controller, the initialization sequence will be performed by PHY */
    HPM_DDRCTL->INIT0 = DDRCTL_INIT0_SKIP_DRAM_INIT_SET(1)
                        | DDRCTL_INIT0_POST_CKE_X1024_SET(2)    /* Default setting */
                        | DDRCTL_INIT0_PRE_CKE_X1024_SET(0x4e); /* Default setting */
    HPM_DDRCTL->DRAMTMG4 = 0x05010407;

    /* Configure DFI timing */
    HPM_DDRCTL->DFITMG0 = 0x07040102;
    HPM_DDRCTL->DFITMG1 = 0x20404;
    HPM_DDRCTL->DFIUPD1 = 0x20008;
    HPM_DDRCTL->ODTCFG = 0x06000600UL;    /* BL=8 */
    HPM_DDRCTL->ODTMAP = 0x11;

    /* Configure ADDRMAP */
    HPM_DDRCTL->ADDRMAP0 = 0x001F1F1FUL;  /* RANK0 not used */
    HPM_DDRCTL->ADDRMAP1 = 0x00121212UL;  /* HIF bit[24:22] as BANK[2:0] */
    HPM_DDRCTL->ADDRMAP2 = 0;             /* HIF bit[6:3] as COL_B[6:3] */
    HPM_DDRCTL->ADDRMAP3 = 0;             /* HIF bit [10:7] as COL_B[11,9:6:7] */
    HPM_DDRCTL->ADDRMAP4 = 0xF0FUL;       /* not used */
    HPM_DDRCTL->ADDRMAP5 = 0x06030303UL;  /* HIF bit[21:11] as ROW[10:0], HIF bit[25] as ROW[11] */
    HPM_DDRCTL->ADDRMAP6 = 0x0F060606UL;  /* HIF bit[27:26] as ROW[13:12] */

    /* Release DDR AXI reset */
    *(volatile uint32_t *) (HPM_DDRCTL_BASE + 0x3000UL) |= (1UL << 27);

    /* Configure DDR3 registers */
    HPM_DDRPHY->MR0 = 0xC70;
    HPM_DDRPHY->MR1 = 0x6;
    HPM_DDRPHY->MR2 = 0x18;
    HPM_DDRPHY->MR3 = 0;

    HPM_DDRPHY->ODTCR = 0x84210000;

    HPM_DDRPHY->DTPR0 = 0x919c8866;
    HPM_DDRPHY->DTPR1 = 0x1a838360;
    HPM_DDRPHY->DTPR2 = 0x3002d200;

    /* tREFPRD */
    HPM_DDRPHY->PGCR2 = 0xf06d28;

    /* Set DFI_INIT_COMPLETE_EN bit */
    HPM_DDRCTL->DFIMISC |= DDRCTL_DFIMISC_DFI_INIT_COMPLETE_EN_MASK;

    /* Start PHY Init First */
    HPM_DDRPHY->PIR |= DDRPHY_PIR_INIT_MASK;
    while ((HPM_DDRPHY->PGSR0 & DDRPHY_PGSR0_IDONE_MASK) == 0) {
    }
    /** Data training
     * RANKEN = 1, Others: default value
     */
    HPM_DDRPHY->DTCR = 0x930035D7;

    /* Trigger PHY to do the PHY initialization and DRAM initialization */
    HPM_DDRPHY->PIR = 0xFF81UL;

    /* Wait until the initialization sequence started */
    while ((HPM_DDRPHY->PGSR0 & DDRPHY_PGSR0_IDONE_MASK) != 0) {
    }
    /* Wait until the initialization sequence completed */
    while ((HPM_DDRPHY->PGSR0 & DDRPHY_PGSR0_IDONE_MASK) == 0) {
    }

    /* Wait for normal mode */
    while ((HPM_DDRCTL->STAT & DDRCTL_STAT_OPERATING_MODE_MASK) != 0x1) {
    }
}

void _init_ext_ram(void)
{
#if (BOARD_DDR_TYPE == DDR_TYPE_DDR2)
    init_ddr2_800();
#endif
#if (BOARD_DDR_TYPE == DDR_TYPE_DDR3L)
    init_ddr3l_1333();
#endif
}

void board_init_usb_pins(void)
{
    init_usb_pins();
    usb_hcd_set_power_ctrl_polarity(BOARD_USB, true);
}

void board_usb_vbus_ctrl(uint8_t usb_index, uint8_t level)
{
    (void) usb_index;
    (void) level;
}

uint32_t board_sd_configure_clock(SDXC_Type *ptr, uint32_t freq, bool need_inverse)
{
    uint32_t actual_freq = 0;
    do {
        if ((ptr != HPM_SDXC0) && (ptr != HPM_SDXC1)) {
            break;
        }
        clock_name_t sdxc_clk = (ptr == HPM_SDXC0) ? clock_sdxc0 : clock_sdxc1;
        clock_add_to_group(sdxc_clk, 0);
        sdxc_enable_inverse_clock(ptr, false);
        sdxc_enable_sd_clock(ptr, false);


        clock_set_source_divider(sdxc_clk, clk_src_pll1_clk0, 4U);
        /* Configure the clock below 400KHz for the identification state */
        if (freq <= 400000UL) {
            /* Set clock to 375KHz */
            sdxc_set_clock_divider(ptr, 534U);
        }
            /* configure the clock to 24MHz for the SDR12/Default speed */
        else if (freq <= 26000000UL) {
            /* Set clock to 25MHz */
            sdxc_set_clock_divider(ptr, 8U);
        }
            /* Configure the clock to 50MHz for the SDR25/High speed/50MHz DDR/50MHz SDR */
        else if (freq <= 52000000UL) {
            /* Set clock to 50MHz */
            sdxc_set_clock_divider(ptr, 4U);
        }
            /* Configure the clock to 100MHz for the SDR50 */
        else if (freq <= 100000000UL) {
            /* Set clock to 100MHz */
            sdxc_set_clock_divider(ptr, 2U);
        }
            /* Configure the clock to 166MHz for SDR104/HS200/HS400  */
        else if (freq <= 208000000UL) {
            /* 166MHz */
            clock_set_source_divider(sdxc_clk, clk_src_pll1_clk1, 4U);
            sdxc_set_clock_divider(ptr, 1U);
        }
            /* For other unsupported clock ranges, configure the clock to 24MHz */
        else {
            /* Set clock to 25MHz */
            sdxc_set_clock_divider(ptr, 5U);
        }
        if (need_inverse) {
            sdxc_enable_inverse_clock(ptr, true);
        }
        sdxc_enable_sd_clock(ptr, true);
        actual_freq = clock_get_frequency(sdxc_clk) / sdxc_get_clock_divider(ptr);
    } while (false);

    return actual_freq;
}

uint32_t board_init_dao_clock(void)
{
    return clock_get_frequency(clock_dao);
}

uint32_t board_init_pdm_clock(void)
{
    return clock_get_frequency(clock_pdm);
}

uint32_t board_init_i2s_clock(I2S_Type *ptr)
{
    if (ptr == HPM_I2S0) {
        return clock_get_frequency(clock_i2s0);
    } else if (ptr == HPM_I2S1) {
        return clock_get_frequency(clock_i2s1);
    } else if (ptr == HPM_I2S2) {
        return clock_get_frequency(clock_i2s2);
    } else if (ptr == HPM_I2S3) {
        return clock_get_frequency(clock_i2s3);
    } else {
        return 0;
    }
}

/* adjust I2S source clock base on sample rate */
uint32_t board_config_i2s_clock(I2S_Type *ptr, uint32_t sample_rate)
{
    if (ptr == HPM_I2S0) {
        if ((sample_rate % 22050) == 0) {
            clock_set_source_divider(clock_aud0, clk_src_pll1_clk0, 71); /* config clock_aud1 for 22050*n sample rate */
            clock_add_to_group(clock_i2s0, 0);
            clock_set_i2s_source(clock_i2s0, clk_i2s_src_aud0);
        } else {
            clock_set_source_divider(clock_aud0, clk_src_pll3_clk0, 21); /* default 24576000Hz */
            clock_add_to_group(clock_i2s0, 0);
            clock_set_i2s_source(clock_i2s0, clk_i2s_src_aud0);
        }
        return clock_get_frequency(clock_i2s0);
    } else if (ptr == HPM_I2S1) {
        if ((sample_rate % 22050) == 0) {
            clock_set_source_divider(clock_aud1, clk_src_pll1_clk0, 71); /* config clock_aud1 for 22050*n sample rate */
            clock_add_to_group(clock_i2s1, 0);
            clock_set_i2s_source(clock_i2s1, clk_i2s_src_aud1);
        } else {
            clock_set_source_divider(clock_aud1, clk_src_pll3_clk0, 21); /* default 24576000Hz */
            clock_add_to_group(clock_i2s1, 0);
            clock_set_i2s_source(clock_i2s1, clk_i2s_src_aud1);
        }
        return clock_get_frequency(clock_i2s1);
    } else if (ptr == HPM_I2S3) {
        if ((sample_rate % 22050) == 0) {
            clock_set_source_divider(clock_aud3, clk_src_pll1_clk0, 71); /* config clock_aud1 for 22050*n sample rate */
            clock_add_to_group(clock_i2s3, 0);
            clock_set_i2s_source(clock_i2s3, clk_i2s_src_aud3);
        } else {
            clock_set_source_divider(clock_aud3, clk_src_pll3_clk0, 21); /* default 24576000Hz */
            clock_add_to_group(clock_i2s3, 0);
            clock_set_i2s_source(clock_i2s3, clk_i2s_src_aud3);
        }
        return clock_get_frequency(clock_i2s3);
    }
    return 0;
}

hpm_stat_t board_init_enet_pins(ENET_Type *ptr)
{
    init_enet_pins(ptr);

    if (ptr == HPM_ENET0) {
        gpio_set_pin_output_with_initial(BOARD_ENET_RGMII_RST_GPIO, BOARD_ENET_RGMII_RST_GPIO_INDEX,
                                         BOARD_ENET_RGMII_RST_GPIO_PIN, 0);
    } else {
        return status_invalid_argument;
    }

    return status_success;
}

hpm_stat_t board_reset_enet_phy(ENET_Type *ptr)
{
    if (ptr == HPM_ENET0) {
        gpio_write_pin(BOARD_ENET_RGMII_RST_GPIO, BOARD_ENET_RGMII_RST_GPIO_INDEX, BOARD_ENET_RGMII_RST_GPIO_PIN, 0);
        board_delay_ms(1);
        gpio_write_pin(BOARD_ENET_RGMII_RST_GPIO, BOARD_ENET_RGMII_RST_GPIO_INDEX, BOARD_ENET_RGMII_RST_GPIO_PIN, 1);
    } else {
        return status_invalid_argument;
    }

    return status_success;
}

uint8_t board_get_enet_dma_pbl(ENET_Type *ptr)
{
    (void) ptr;
    return enet_pbl_32;
}

hpm_stat_t board_enable_enet_irq(ENET_Type *ptr)
{
    if (ptr == HPM_ENET0) {
        intc_m_enable_irq(IRQn_ENET0);
    } else {
        return status_invalid_argument;
    }

    return status_success;
}

hpm_stat_t board_disable_enet_irq(ENET_Type *ptr)
{
    if (ptr == HPM_ENET0) {
        intc_m_disable_irq(IRQn_ENET0);
    } else {
        return status_invalid_argument;
    }

    return status_success;
}

void board_init_enet_pps_pins(ENET_Type *ptr)
{
    (void) ptr;
    init_enet_pps_pins();
}

hpm_stat_t board_init_enet_ptp_clock(ENET_Type *ptr)
{
    /* set clock source */
    if (ptr == HPM_ENET0) {
        /* make sure pll0_clk0 output clock at 800MHz to get a clock at 100MHz for the enet0 ptp function */
        clock_set_source_divider(clock_ptp0, clk_src_pll1_clk0, 8); /* 100MHz */
    } else {
        return status_invalid_argument;
    }

    return status_success;
}

hpm_stat_t board_init_enet_rmii_reference_clock(ENET_Type *ptr, bool internal)
{
    (void) ptr;
    (void) internal;
    return status_success;
}

hpm_stat_t board_init_enet_rgmii_clock_delay(ENET_Type *ptr)
{
    if (ptr == HPM_ENET0) {
        return enet_rgmii_set_clock_delay(ptr, BOARD_ENET_RGMII_TX_DLY, BOARD_ENET_RGMII_RX_DLY);
    }

    return status_invalid_argument;
}

void board_init_adc16_pins(void)
{
    init_adc_pins();
}

uint32_t board_init_adc16_clock(ADC16_Type *ptr, bool clk_src_ahb)
{
    uint32_t freq = 0;

    if (ptr == HPM_ADC0) {
        if (clk_src_ahb) {
            /* Configure the ADC clock from AXI (@200MHz by default)*/
            clock_set_adc_source(clock_adc0, clk_adc_src_ahb0);
        } else {
            /* Configure the ADC clock from pll0_clk1 divided by 4 (@200MHz by default) */
            clock_set_adc_source(clock_adc0, clk_adc_src_ana0);
            clock_set_source_divider(clock_ana0, clk_src_pll1_clk0, 4U);
        }

        freq = clock_get_frequency(clock_adc0);
    }

    return freq;
}

uint32_t board_init_sadc_clock(SDADC_Type *ptr, bool clk_src_ahb)
{
    uint32_t freq = 0;

    if (ptr == HPM_ADC1) {
        if (clk_src_ahb) {
            /* Configure the ADC clock from AXI (@200MHz by default)*/
            clock_set_adc_source(clock_adc1, clk_adc_src_ahb0);
        } else {
            /* Configure the ADC clock from pll1_clk1 divided by 2 (@200MHz by default) */
            clock_set_adc_source(clock_adc1, clk_adc_src_ana1);
            clock_set_source_divider(clock_ana1, clk_src_pll1_clk0, 4U);
        }

        freq = clock_get_frequency(clock_adc1);
    }

    return freq;
}
